package cn.wawi.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import cn.wawi.common.Json;
import cn.wawi.common.annotation.Permission;
import cn.wawi.common.easyui.DataGrid;
import cn.wawi.controller.BaseController;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.entity.sys.Role;
import cn.wawi.utils.QueryUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/sys_role")
public class RoleController extends BaseController<Role>{
	
	@ResponseBody
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public DataGrid list(HttpServletRequest request){
		return findAllByPage(request);
	}
	/*
	 * 权限列表
	 */
	@ResponseBody
	@RequestMapping(value="/pList",method=RequestMethod.GET)
	public DataGrid pLlist(HttpServletRequest request){
		Map<String,Object> map=QueryUtil.setPage(request,1,500);
		List<Privilege> list = privilegeDao.findAll(map);
		PageInfo<Privilege> pages = new PageInfo<Privilege>(list);
		DataGrid dataGrid=new DataGrid(pages.getList(),pages.getTotal());
		return dataGrid;
	}
	@ResponseBody
	@RequestMapping(value="/getUserRole",method=RequestMethod.GET)
	public List<Role> getUserRole(long userId){
		return roleDao.getUserRole(userId);
	}
	/*
	 * 保存用户角色
	 */
	@Permission("sys:user:roleUpdate")
	@ResponseBody
	@RequestMapping(value="/saveUser",method=RequestMethod.POST)
	public Json saveUser(long userId,String roleId){
		roleDao.deleteUser(userId);
		if(roleId!=null&&!"".equals(roleId.trim())){
			for (String s: roleId.split(",")) {
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("userId",userId);
				map.put("roleId", s);
				roleDao.saveUser(map);
			}
		}
		return new Json("saveUser", "保存用户角色!");
	}
	
	@ResponseBody
	@RequestMapping(value="/getPrivilege",method=RequestMethod.GET)
	public List<Privilege> getPrivilege(Long id){
		List<Privilege> list=privilegeDao.findRolePrivilege(id);
		return list;
	}
	/*
	 * 保存角色权限
	 */
	@Permission("sys:role:savePrivilege")
	@ResponseBody
	@RequestMapping(value="/savePrivilege",method=RequestMethod.POST)
	public Json savePrivilege(String roleId,String privilegeIds){
		roleDao.delete(roleId);
		if(privilegeIds!=null&&!"".equals(privilegeIds.trim())){
			String[] privileges=privilegeIds.split(",");
			for (String p: privileges) {
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("roleId", roleId);
				map.put("privilegeId", p);
				roleDao.savePrivilege(map);
			}
		}
		return new Json("save", "添加用户信息!");
	}
}
